package com.it;

import cn.hutool.core.util.ReflectUtil;
import tk.mybatis.mapper.util.StringUtil;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

/**
 * @author TBH
 * 获取类的字段只包含字符串 数值 数据库中有的字段 排除复合类型
 */
public class JavaBeanFields {

    private static final String SERVICE_SUFFIX = "Service";
    private static final String DAO_SUFFIX = "Dao";

    private static final String STR_TYPE = "java.lang.String";
    private static final String INT_TYPE = "java.lang.Integer";
    private static final String LONG_TYPE = "java.lang.Long";
    private static final String DATE_TYPE = "java.util.Date";
    private static final String BOOLEAN_TYPE = "java.lang.Boolean";
    private static final String ENCRYPT_TYPE = "team.yichun.bean.Encrypt";

    private static final List<String> EXCLUDE_TYPE = new ArrayList<String>() {{
        add(STR_TYPE);
        add(INT_TYPE);
        add(LONG_TYPE);
        add(DATE_TYPE);
        add(ENCRYPT_TYPE);
        add(BOOLEAN_TYPE);
    }};

    public static List<String> fields(String name) throws Exception {
        Class<?> type = Class.forName(name);
        Field[] fs = ReflectUtil.getFields(type);
        List<String> fields = new ArrayList<>(fs.length);
        for (Field f : fs) {
            if (EXCLUDE_TYPE.contains(f.getType().getName())) {
                //使用mybatis-plus的驼峰映射法
                fields.add(StringUtil.camelhumpToUnderline(f.getName()));
            }
        }
        return fields;
    }

    public static String joinFields(String name, String prefix) throws Exception {
        List<String> fields = fields(name);
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < fields.size(); i++) {
            sb.append(prefix);
            sb.append(".`");
            sb.append(fields.get(i));
            sb.append("` AS ");
            sb.append(prefix);
            sb.append("_");
            sb.append(fields.get(i));
            if (i != fields.size() - 1) {
                sb.append(",");
            }
        }
        return sb.toString();
    }

    public static void main(String[] args) throws Exception {
        String user = joinFields("com.it.bean.Notice", "sn");
        System.out.println(user);
    }
}
